package org.cuit.echo.seon;

import javax.swing.*;
import java.awt.*;

/**
 * @author SeonExlike
 * @since 2024/3/20
 */
public class VisualSingleton {
    public static void main(String[] args) {
        SingletonWindow singletonTestWindow = new SingletonWindow();
    }
}

class SingletonWindow {
    public SingletonWindow() {
        JFrame frame = new JFrame("单例模式");
        frame.setSize(1024, 768);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        frame.add(panel);
        panel.setLayout(null);
        Button button = new Button("打开工具箱");
        button.setBounds(10, 10, 120, 25);
        button.addActionListener(e -> Toolkit.getInstance());
        panel.add(button);

        Button button2 = new Button("打开工具箱");
        button2.setBounds(130, 10, 120, 25);
        button2.addActionListener(e -> Toolkit.getInstance());
        panel.add(button2);

        frame.setVisible(true);
    }
}

/**
 * 使用图形化的方法解释了为什么要使用单例模式，很nice
 */
class Toolkit extends JFrame {
    private static Toolkit toolkit;

    private Toolkit(String title) {
        super(title);
    }

    public static Toolkit getInstance() {
        if (toolkit == null || !toolkit.isVisible()) {
            toolkit = new Toolkit("工具箱");
            toolkit.setSize(150, 300);
            toolkit.setLocation(100, 100);
            toolkit.setResizable(false);
            toolkit.setAlwaysOnTop(true);
            toolkit.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            toolkit.setVisible(true);
        }
        return toolkit;
    }
}